package com.yugao.fintech.antelope.auth.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson2.JSON;
import com.yugao.fintech.antelope.auth.assembly.ThirdAuthAssembly;
import com.yugao.fintech.antelope.auth.model.rqrs.third.ThirdAuthUser;
import com.yugao.fintech.antelope.auth.model.rqrs.third.WxMaLoginReq;
import com.yugao.fintech.antelope.auth.service.WxAuthService;
import com.yugao.fintech.antelope.base.dynamic.AbstractClientProcess;
import com.yugao.fintech.antelope.base.dynamic.wx.WxMaWrapClient;
import com.yugao.fintech.antelope.base.dynamic.wx.WxMpWrapClient;
import com.yugao.fintech.antelope.base.log.OperateLog;
import com.yugao.fintech.antelope.base.model.enums.AuthErrorEnum;
import com.yugao.fintech.antelope.base.model.enums.ConfigDefineEnum;
import com.yugao.fintech.framework.assistant.utils.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Slf4j
@Service
public class WxAuthServiceImpl implements WxAuthService {
    @Autowired
    private ThirdAuthAssembly thirdAuthAssembly;

    @Override
    @OperateLog(isSaveDb = false)
    public ThirdAuthUser getWxLoginInfo(WxMaLoginReq req) throws WxErrorException {
        try {
            WxMpWrapClient wxMpService = ((WxMpWrapClient) AbstractClientProcess.getDynamicClient(ConfigDefineEnum.WX_MP));
            WxMaService wxMaService = ((WxMaWrapClient) AbstractClientProcess.getDynamicClient(ConfigDefineEnum.WX_MA)).getWxMaService();
            WxMaJscode2SessionResult sessionResult = wxMaService.jsCode2SessionInfo(req.getCode());
            log.info("微信登录- req: {}, res: {}", JSON.toJSONString(req), sessionResult);
            if (Objects.isNull(sessionResult)) {
                throw new BizException(AuthErrorEnum.TOKEN_EXPIRED);
            }

            // 解密用户信息
            WxMaUserInfo wxUserInfo = wxMaService.getUserService().getUserInfo(sessionResult.getSessionKey(),
                    req.getEncryptedData(), req.getIv());
            if (null == wxUserInfo) {
                throw new BizException(AuthErrorEnum.WX_USER_NOT_EXIST);
            }
            ThirdAuthUser thirdAuthUser = thirdAuthAssembly.toThirdAuthUser(wxUserInfo);

            thirdAuthUser.setOpenId(sessionResult.getOpenid());
            return thirdAuthUser;
        } catch (WxRuntimeException e) {
            log.error("error: ", e);
            throw new BizException(AuthErrorEnum.WX_DATA_PARSE_FAIL);
        }
    }
}
